﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Commander.DataLayer.Entities;
using NHibernate;
using NHibernate.Criterion;

namespace Commander.DataLayer.Repositories {
  public interface ICommanderUserRepository {
    bool IsUser(string username, string password);
    Guid GetId(string username, string password);

    IList<CommanderProject> GetProjectConfig(string username, string password);
  }
  public class CommanderUserRepository : DomainRepository<CommanderUser>, ICommanderUserRepository {
   public bool IsUser(string username, string password) {
     using (ISession session = NHibernateSessionHelper.OpenSession()) {
       var user = session.CreateCriteria<CommanderUser>()
                          .Add(Restrictions.Eq("UserId", username))
                          .Add(Restrictions.Eq("Password", password))
                          .UniqueResult<CommanderUser>();
       return user != null;
     }
   }


   public Guid GetId(string username, string password) {
     using (ISession session = NHibernateSessionHelper.OpenSession()) {
       var user = session.CreateCriteria<CommanderUser>()
                          .Add(Restrictions.Eq("UserId", username))
                          .Add(Restrictions.Eq("Password", password))
                          .UniqueResult<CommanderUser>();

       if (user != null) {
         return user.Id;
       }
       else {
         return Guid.Empty;
       }
     }
   }


   public IList<CommanderProject> GetProjectConfig(string username, string password) {
     using (ISession session = NHibernateSessionHelper.OpenSession()) {
       var user = session.CreateCriteria<CommanderUser>()
                          .Add(Restrictions.Eq("UserId", username))
                          .Add(Restrictions.Eq("Password", password))
                          .SetFetchMode("Projects", FetchMode.Eager)
                          .UniqueResult<CommanderUser>();

       if (user != null) {
         return user.Projects;
       }
       else {
         return null;
       }

     }
   }
  }
}
